package stiletto.login.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 82022170
 * Date: 13. 10. 21
 * Time: 오후 5:35
 * To change this template use File | Settings | File Templates.
 */
public class LoginServlet extends HttpServlet {
  private static Log log;
  private Map<String, String> users;

  @Override
  public void init() throws ServletException {
    users = new HashMap<String, String>();
    users.put("ryudaewan@gmail.com", "thebest-1");
    users.put("falcon@daum.net", "aligator$2");
    log = LogFactory.getLog(this.getClass());
  }

  @Override
  public void destroy() {
    LogFactory.release(this.getClass().getClassLoader());
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String id = "";
    String password = "";
    String jsonVal = "login.";
    Map<String, String> responseJson = new HashMap<String, String>();
    HttpSession session = null;

    id = request.getParameter("tId");
    password = request.getParameter("tPassword");

    if (log.isDebugEnabled()) log.debug("tId = " + id + "\ntPassword = " + password);

    if (null == id || !this.users.containsKey((id = id.trim()))) {
      jsonVal += "invalidEmail";
    } else if (null == password || !password.trim().equals(this.users.get(id))) {
      jsonVal += "invalidPassword";
    } else {
      session = request.getSession(true);
      session.setAttribute("id", id);
      session.setAttribute("loginTime", System.currentTimeMillis());
      jsonVal += "success";
    }

    responseJson.put("message", jsonVal);
    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    try {
      String json = (new ObjectMapper()).writer().writeValueAsString(responseJson);
      if (log.isDebugEnabled()) log.debug(json);
      response.getWriter().write(json);
    } catch (JsonGenerationException jge) {
      if (log.isErrorEnabled()) log.error(exceptionMsg("JSON 생성 도중 예외 발생"), jge);
      throw new ServletException(jge);
    } catch (JsonMappingException jme) {
      if (log.isErrorEnabled()) log.error(exceptionMsg("JSON 매핑 도중 예외 발생"), jme);
      throw new ServletException(jme);
    } catch (IOException ioe) {
      if (log.isErrorEnabled()) log.error(exceptionMsg("Response 쓰는 도중 예외 발생"), ioe);
      throw new ServletException(ioe);
    }

  }

  private String exceptionMsg(String msg) {
    return "[" + this.getClass().getCanonicalName() + "] " + msg;
  }
}
